package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/30 19:54
 */

@Component
@Slf4j
public class OrderTask {
    @Resource
    private OrderMapper orderMapper;

    /**
     * 处理待付款订单超时15分钟未付款的问题
     * cron = "0 1 * * * ? *" 每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processOrderTimeout() {
        log.info("处理待付款订单超时15分钟未付款的问题");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list = orderMapper.getByStatusWithOrderTime(Orders.PENDING_PAYMENT,time);
        if (list != null && list.size() > 0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("15分钟内未付款订单自动取消");
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理配送订单超时问题
     * 每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryTimeout(){
        log.info("处理配送订单超时问题");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.getByStatusWithOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (list != null && list.size() > 0){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
